package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.controller.utils.DownloadUtil;
import cn.itcast.dao.cargo.ContractProductDao;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.vo.ContractProductVo;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.List;

@Controller
@RequestMapping("/cargo/contract")
public class OutProductController extends BaseController{

    @Reference
    private ContractProductService contractProductService;
    /**
     * 导出出货表（1）进入页面contract-print.jsp
     */
    @RequestMapping("/print")
    public String print(){
        return "cargo/print/contract-print";
    }

    /**
     * 导出出货表（2）导出excel，完整实现
     */
    @RequestMapping("/printExcel")
    public void printExcel(String inputDate) throws Exception {
        //第一步：创建工作簿，创建工作表
        Workbook workbook = new SXSSFWorkbook();
        Sheet sheet = workbook.createSheet("出货表");
        // 设置列宽
        sheet.setColumnWidth(0, 256*5);
        sheet.setColumnWidth(1, 256*5);
        sheet.setColumnWidth(2, 256*25);
        sheet.setColumnWidth(3, 256*11);
        sheet.setColumnWidth(4, 256*29);
        sheet.setColumnWidth(5, 256*16);
        sheet.setColumnWidth(6, 256*14);
        sheet.setColumnWidth(7, 256*10);
        sheet.setColumnWidth(8, 256*10);

        //第二步：导出第一行(大标题：2012年8月份出货表)
        // 合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));
        // 创建第一行
        Row row = sheet.createRow(0);
        // 设置行高
        row.setHeightInPoints(26);
        // 创建第一行的第二列
        Cell cell = row.createCell(1);
        // 给第一行的第二列赋值: 2015-01 转换为2015年1月份出货表   2015-1
        String value = inputDate.replace("-0","-").replace("-","年") + "月份出货表";
        cell.setCellValue(value);
        // 设置样式
        cell.setCellStyle(this.bigTitle(workbook));

        //第二步：导出第二行（小标题：客户	订单号	货号	数量	工厂	工厂交期	船期	贸易条款）
        row = sheet.createRow(1);
        row.setHeightInPoints(26);
        String[] titles={"客户","订单号","货号","数量","工厂","工厂交期","船期","贸易条款"};
        for(int i=0; i<titles.length; i++){
            cell = row.createCell(i+1);
            cell.setCellValue(titles[i]);
            cell.setCellStyle(this.title(workbook));
        }

        //第三步：导出数据行
        List<ContractProductVo> list =
                contractProductService.findByShipTime(inputDate, getLoginCompanyId());
        if (list != null && list.size()>0){
            int index = 2;
            for (ContractProductVo vo : list) {
                for (int i=0; i<6000; i++) {
                    // 创建数据行，从第3行开始
                    row = sheet.createRow(index++);
                    // 创建列，给列设置值
                    cell = row.createCell(1);
                    cell.setCellValue(vo.getCustomName());
                   // cell.setCellStyle(this.title(workbook));

                    cell = row.createCell(2);
                    cell.setCellValue(vo.getContractNo());
                   // cell.setCellStyle(this.title(workbook));

                    cell = row.createCell(3);
                    cell.setCellValue(vo.getProductNo());
                    //cell.setCellStyle(this.title(workbook));

                    cell = row.createCell(4);
                    cell.setCellValue(vo.getCnumber());
                   // cell.setCellStyle(this.title(workbook));

                    cell = row.createCell(5);
                    cell.setCellValue(vo.getFactoryName());
                   // cell.setCellStyle(this.title(workbook));

                    cell = row.createCell(6);
                    cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(vo.getDeliveryPeriod()));
                  //  cell.setCellStyle(this.title(workbook));

                    cell = row.createCell(7);
                    cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(vo.getShipTime()));
                   // cell.setCellStyle(this.title(workbook));

                    cell = row.createCell(8);
                    cell.setCellValue(vo.getTradeTerms());
                   // cell.setCellStyle(this.title(workbook));
                }
            }
        }

        //第四步：导出下载
        // 创建缓冲流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        // 把内存中构建的excel写入到缓冲流
        workbook.write(bos);
        // 下载
        new DownloadUtil().download(bos,response,"出货表.xlsx");
        // 关闭
        workbook.close();
    }


    /** 导出excel： 模板导出
    @RequestMapping("/printExcel")
    public void printExcel(String inputDate) throws Exception {
        //第一步：读取excel模板，创建工作簿，获取工作表
        InputStream in = session.getServletContext().getResourceAsStream("/make/xlsprint/tOUTPRODUCT.xlsx");
        Workbook workbook = new XSSFWorkbook(in);
        // 获取工作表
        Sheet sheet = workbook.getSheetAt(0);

        // 获取第一行
        Row row = sheet.getRow(0);
        // 获取第一行的第二列
        Cell cell = row.getCell(1);
        String value = inputDate.replace("-0","-").replace("-","年") + "月份出货表";
        cell.setCellValue(value);


        //第二步：获取第三行样式
        row = sheet.getRow(2);
        CellStyle[] cellStyles= new CellStyle[8];
        for(int i=0; i<cellStyles.length; i++){
            cellStyles[i] = row.getCell(i+1).getCellStyle();
        }

        //第三步：导出数据行
        List<ContractProductVo> list =
                contractProductService.findByShipTime(inputDate, getLoginCompanyId());
        if (list != null && list.size()>0){
            int index = 2;
            for (ContractProductVo vo : list) {
                // 创建数据行，从第3行开始
                row = sheet.createRow(index++);
                // 创建列，给列设置值
                cell = row.createCell(1);
                cell.setCellValue(vo.getCustomName());
                cell.setCellStyle(cellStyles[0]);

                cell = row.createCell(2);
                cell.setCellValue(vo.getContractNo());
                cell.setCellStyle(cellStyles[1]);

                cell = row.createCell(3);
                cell.setCellValue(vo.getProductNo());
                cell.setCellStyle(cellStyles[2]);

                cell = row.createCell(4);
                cell.setCellValue(vo.getCnumber());
                cell.setCellStyle(cellStyles[3]);

                cell = row.createCell(5);
                cell.setCellValue(vo.getFactoryName());
                cell.setCellStyle(cellStyles[4]);

                cell = row.createCell(6);
                cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(vo.getDeliveryPeriod()));
                cell.setCellStyle(cellStyles[5]);

                cell = row.createCell(7);
                cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(vo.getShipTime()));
                cell.setCellStyle(cellStyles[6]);

                cell = row.createCell(8);
                cell.setCellValue(vo.getTradeTerms());
                cell.setCellStyle(cellStyles[7]);
            }
        }

        //第四步：导出下载
        // 创建缓冲流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        // 把内存中构建的excel写入到缓冲流
        workbook.write(bos);
        // 下载
        new DownloadUtil().download(bos,response,"出货表.xlsx");
        // 关闭
        workbook.close();
    }
    */



    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);				//横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线

        return style;
    }
}
